package org.apache.cordova.plugin;

import android.content.Context;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.DataOutputStream;

import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class ShellExec extends CordovaPlugin {

@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {

        if (action.equals("exec")) {
                        Process process;
                        JSONObject json = new JSONObject();
                        StringBuffer sout = new StringBuffer();
                        int exitStatus = 100;
                        try {
                                json.put("cmd0", args.get(0));
                                process = Runtime.getRuntime().exec((String) args.get(0));
                                BufferedReader reader = new BufferedReader(
                                                new InputStreamReader(process.getInputStream()));
                                DataOutputStream outstrm = new DataOutputStream(process.getOutputStream());
                                for (int i = 1; i < args.length(); i++) {
                                        outstrm.writeBytes(args.get(i) + "\n");
                                        json.put("cmd" + i, args.get(i));
                                }
                                if (args.length() > 1) {
                                        outstrm.flush();
                                }
                                String line = "";
                                while ((line = reader.readLine()) != null) {
                                        sout.append(line + "\n");
                                }
                                exitStatus = process.waitFor();
                        } catch (IOException e) {
                                e.printStackTrace();
                        } catch (InterruptedException e) {
                                e.printStackTrace();
                        }
                        json.put("exitStatus", exitStatus);
                        json.put("output", sout.toString());
                        callbackContext.success(json);
                        return true;
                }
                return false;
        }

}
